/**
 *    Copyright 2010 Merrick Zhang ( anphorea@gmail.com )
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
package anpho.proxyvalidator.output;

import java.net.InetSocketAddress;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Set;

import anpho.proxyvalidator.bean.ProxyBean;
import anpho.proxyvalidator.config.AppContext;

/**
 * @author Merrick
 * @version 1.01
 */
public class Output2Console implements IOutput {

	/*
	 * (non-Javadoc)
	 * @see anpho.proxyvalidator.output.IOutput#print(java.util.Set,
	 * java.lang.String[])
	 */
	@Override
	public void print(Set<ProxyBean> pb, Object... args) {
		ProxyBean[] sortted = sortedfilter(pb);
		System.out.println("+OK Results");
		for (ProxyBean p : sortted) {
			InetSocketAddress i = (InetSocketAddress) p._proxy.address();
			System.out.println(MessageFormat.format("{0}:{1,number,#####} \tFailRate={2}% \tAverageTime={3}ms",
					i.getAddress().getHostAddress(), i.getPort(), p.getFailRate() * 100, p.getAvgTime()));
		}
	}

	/**
	 * Sort the set and filter out the bad Proxies.
	 * 
	 * @param pb
	 * @return
	 */
	public ProxyBean[] sortedfilter(Set<ProxyBean> pb) {
		// transform into array
		ProxyBean[] sorttedSet = pb.toArray(new ProxyBean[pb.size()]);
		// sort the array using the comparator.
		int sortby = AppContext.getInt("SORTBY");
		if (sortby == 1) {
			Arrays.sort(sorttedSet, new PBComparatorByAvgTime());
		} else {
			Arrays.sort(sorttedSet, new PBComparatorByFailRate());
		}
		return sorttedSet;
	}

	/**
	 * comparator of the ProxyBean class,this will sort the set by each item's
	 * failure rate.
	 * 
	 * @author Merrick
	 */
	class PBComparatorByAvgTime implements Comparator<ProxyBean> {

		/*
		 * (non-Javadoc)
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		@Override
		public int compare(ProxyBean o1, ProxyBean o2) {
			return (int) ((o1.getAvgTime() - o2.getAvgTime()));
		}

	}

	class PBComparatorByFailRate implements Comparator<ProxyBean> {

		/*
		 * (non-Javadoc)
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		@Override
		public int compare(ProxyBean o1, ProxyBean o2) {
			return (int) ((o1.getFailRate() - o2.getFailRate()) * 100);
		}

	}
}
